"""
路由器方面级情感分析脚本
专门针对路由器产品的多维度情感分析与报告生成
"""

import json
import os
import jieba
import re
import numpy as np
from collections import defaultdict, Counter
from datetime import datetime
import pandas as pd

class RouterAspectSentimentAnalyzer:
    """路由器方面级情感分析器"""
    
    def __init__(self, sentiment_dict_path):
        """初始化分析器"""
        self.sentiment_dict = self._load_sentiment_dict(sentiment_dict_path)
        
        # 路由器专业方面定义（更细化）
        self.router_aspects = {
            "网络性能": {
                "keywords": ["网速", "速度", "快", "慢", "带宽", "吞吐量", "传输", "下载", "上传", "延迟", "ping", "卡顿"],
                "description": "网络传输速度和性能表现",
                "weight": 1.0
            },
            "信号稳定性": {
                "keywords": ["稳定", "掉线", "断线", "连接", "重启", "死机", "故障", "不稳", "卡", "断网", "重连"],
                "description": "网络连接的稳定性和可靠性",
                "weight": 1.0
            },
            "信号覆盖": {
                "keywords": ["覆盖", "穿墙", "距离", "范围", "死角", "盲区", "信号强度", "信号", "远", "近", "楼层"],
                "description": "WiFi信号的覆盖范围和穿透能力",
                "weight": 0.9
            },
            "易用性": {
                "keywords": ["安装", "配置", "设置", "操作", "界面", "说明书", "使用", "简单", "复杂", "方便", "困难", "APP"],
                "description": "产品的安装配置和使用便捷性",
                "weight": 0.8
            },
            "产品外观": {
                "keywords": ["外观", "设计", "颜色", "体积", "重量", "材质", "工艺", "美观", "好看", "丑", "大小", "造型"],
                "description": "产品的外观设计和制造工艺",
                "weight": 0.6
            },
            "散热性能": {
                "keywords": ["散热", "发热", "温度", "烫", "热", "风扇", "噪音", "静音", "声音"],
                "description": "设备的散热表现和噪音控制",
                "weight": 0.7
            },
            "价格性价比": {
                "keywords": ["价格", "便宜", "贵", "值得", "划算", "实惠", "性价比", "超值", "物超所值", "坑", "不值"],
                "description": "产品的价格定位和性价比表现",
                "weight": 0.8
            },
            "售后服务": {
                "keywords": ["客服", "售后", "服务", "保修", "维修", "退换", "态度", "响应", "解决", "技术支持"],
                "description": "厂商提供的售后服务质量",
                "weight": 0.7
            }
        }
        
        # 情感强度等级
        self.intensity_levels = {
            "非常满意": (0.7, 1.0),
            "比较满意": (0.4, 0.7),
            "一般": (-0.4, 0.4),
            "比较不满": (-0.7, -0.4),
            "非常不满": (-1.0, -0.7)
        }
    
    def _load_sentiment_dict(self, dict_path):
        """加载情感词典"""
        try:
            with open(dict_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            print(f"❌ 加载情感词典失败: {e}")
            return {}
    
    def _extract_aspect_sentences(self, text, aspect_keywords):
        """提取包含特定方面关键词的句子"""
        # 按标点符号分句
        sentences = re.split(r'[。！？；，]', text)
        aspect_sentences = []
        
        for sentence in sentences:
            sentence = sentence.strip()
            if not sentence:
                continue
                
            # 检查句子是否包含该方面的关键词
            for keyword in aspect_keywords:
                if keyword in sentence:
                    aspect_sentences.append({
                        "sentence": sentence,
                        "matched_keyword": keyword
                    })
                    break  # 避免同一句子重复匹配
        
        return aspect_sentences
    
    def _analyze_sentence_sentiment(self, sentence):
        """分析单句情感"""
        if not sentence:
            return 0.0, 0.0, []
        
        words = list(jieba.cut(sentence))
        positive_words = self.sentiment_dict.get("正面词汇", {})
        negative_words = self.sentiment_dict.get("负面词汇", {})
        degree_words = self.sentiment_dict.get("程度副词", {})
        negation_words = self.sentiment_dict.get("否定词", [])
        
        sentiment_scores = []
        found_phrases = []
        
        # 检查完整短语匹配
        for phrase, score in positive_words.items():
            if phrase in sentence:
                # 检查否定
                negated = any(neg in sentence for neg in negation_words if sentence.find(neg) < sentence.find(phrase))
                final_score = -score * 0.8 if negated else score
                sentiment_scores.append(final_score)
                found_phrases.append({
                    "phrase": phrase,
                    "score": final_score,
                    "type": "正面" if final_score > 0 else "负面"
                })
        
        for phrase, score in negative_words.items():
            if phrase in sentence:
                # 检查否定（双重否定变正面）
                negated = any(neg in sentence for neg in negation_words if sentence.find(neg) < sentence.find(phrase))
                final_score = -score * 0.8 if negated else score
                sentiment_scores.append(final_score)
                found_phrases.append({
                    "phrase": phrase,
                    "score": final_score,
                    "type": "正面" if final_score > 0 else "负面"
                })
        
        # 计算最终得分
        if sentiment_scores:
            avg_score = np.mean(sentiment_scores)
            confidence = min(1.0, len(sentiment_scores) * 0.3 + abs(avg_score) * 0.5)
        else:
            avg_score = 0.0
            confidence = 0.0
        
        return avg_score, confidence, found_phrases
    
    def analyze_aspect_sentiment(self, text, aspect_name, aspect_info):
        """分析特定方面的情感"""
        aspect_keywords = aspect_info["keywords"]
        aspect_weight = aspect_info["weight"]
        
        # 提取相关句子
        relevant_sentences = self._extract_aspect_sentences(text, aspect_keywords)
        
        if not relevant_sentences:
            return {
                "aspect_name": aspect_name,
                "description": aspect_info["description"],
                "mentioned": False,
                "sentiment_score": 0.0,
                "confidence": 0.0,
                "intensity_level": "无提及",
                "relevant_sentences": [],
                "sentiment_phrases": [],
                "matched_keywords": []
            }
        
        # 分析每个相关句子的情感
        sentence_scores = []
        all_phrases = []
        matched_keywords = set()
        
        for sent_info in relevant_sentences:
            sentence = sent_info["sentence"]
            keyword = sent_info["matched_keyword"]
            
            score, confidence, phrases = self._analyze_sentence_sentiment(sentence)
            
            if confidence > 0.1:  # 只考虑有一定置信度的句子
                sentence_scores.append({
                    "sentence": sentence,
                    "score": score,
                    "confidence": confidence,
                    "phrases": phrases
                })
                all_phrases.extend(phrases)
                matched_keywords.add(keyword)
        
        # 计算方面整体情感
        if sentence_scores:
            # 加权平均（置信度作为权重）
            total_weight = sum(s["confidence"] for s in sentence_scores)
            if total_weight > 0:
                weighted_score = sum(s["score"] * s["confidence"] for s in sentence_scores) / total_weight
                avg_confidence = total_weight / len(sentence_scores)
            else:
                weighted_score = 0.0
                avg_confidence = 0.0
            
            # 应用方面权重
            final_score = weighted_score * aspect_weight
            
            # 确定强度等级
            intensity_level = self._get_intensity_level(final_score)
        else:
            final_score = 0.0
            avg_confidence = 0.0
            intensity_level = "无明确态度"
        
        return {
            "aspect_name": aspect_name,
            "description": aspect_info["description"],
            "mentioned": True,
            "sentiment_score": round(final_score, 4),
            "confidence": round(avg_confidence, 4),
            "intensity_level": intensity_level,
            "relevant_sentences": [s["sentence"] for s in sentence_scores[:3]],  # 取前3句
            "sentiment_phrases": all_phrases[:5],  # 取前5个短语
            "matched_keywords": list(matched_keywords),
            "sentence_count": len(sentence_scores)
        }
    
    def _get_intensity_level(self, score):
        """根据得分确定强度等级"""
        for level, (min_score, max_score) in self.intensity_levels.items():
            if min_score <= score < max_score:
                return level
        return "一般"
    
    def analyze_comment_aspects(self, comment_text):
        """分析单条评论的所有方面情感"""
        if not comment_text or len(comment_text.strip()) < 3:
            return self._create_empty_aspect_result()
        
        aspect_results = {}
        
        # 分析每个方面
        for aspect_name, aspect_info in self.router_aspects.items():
            aspect_result = self.analyze_aspect_sentiment(comment_text, aspect_name, aspect_info)
            aspect_results[aspect_name] = aspect_result
        
        # 计算整体统计
        mentioned_aspects = [name for name, result in aspect_results.items() if result["mentioned"]]
        avg_score = np.mean([result["sentiment_score"] for result in aspect_results.values() 
                           if result["mentioned"] and result["confidence"] > 0.2])
        
        if np.isnan(avg_score):
            avg_score = 0.0
        
        return {
            "original_text": comment_text,
            "aspect_results": aspect_results,
            "mentioned_aspects": mentioned_aspects,
            "mention_count": len(mentioned_aspects),
            "overall_aspect_score": round(avg_score, 4),
            "overall_intensity": self._get_intensity_level(avg_score),
            "analysis_coverage": round(len(mentioned_aspects) / len(self.router_aspects) * 100, 1)
        }
    
    def _create_empty_aspect_result(self):
        """创建空的方面分析结果"""
        return {
            "original_text": "",
            "aspect_results": {},
            "mentioned_aspects": [],
            "mention_count": 0,
            "overall_aspect_score": 0.0,
            "overall_intensity": "无效评论",
            "analysis_coverage": 0.0
        }
    
    def batch_analyze_aspects(self, comments_data):
        """批量分析评论的方面情感"""
        print(f"🔍 开始方面级情感分析 {len(comments_data)} 条评论...")
        
        results = []
        for i, comment in enumerate(comments_data):
            if i % 50 == 0:
                print(f"  进度: {i}/{len(comments_data)}")
            
            content = comment.get("content", "")
            aspect_analysis = self.analyze_comment_aspects(content)
            
            # 合并到原评论数据
            enhanced_comment = comment.copy()
            enhanced_comment["aspect_analysis"] = aspect_analysis
            
            results.append(enhanced_comment)
        
        print("✅ 方面级分析完成")
        return results

class AspectReportGenerator:
    """方面级情感分析报告生成器"""
    
    def __init__(self):
        self.router_aspects = {
            "网络性能": "网络传输速度和性能表现",
            "信号稳定性": "网络连接的稳定性和可靠性", 
            "信号覆盖": "WiFi信号的覆盖范围和穿透能力",
            "易用性": "产品的安装配置和使用便捷性",
            "产品外观": "产品的外观设计和制造工艺",
            "散热性能": "设备的散热表现和噪音控制",
            "价格性价比": "产品的价格定位和性价比表现",
            "售后服务": "厂商提供的售后服务质量"
        }
    
    def generate_aspect_report(self, analyzed_data, product_name, output_path):
        """生成方面级情感分析报告"""
        print("📊 生成方面级情感分析报告...")
        
        # 1. 汇总方面情感数据
        aspect_summary = self._summarize_aspect_sentiments(analyzed_data)
        
        # 2. 生成各方面详细分析
        aspect_details = self._analyze_aspect_details(analyzed_data)
        
        # 3. 识别关键问题和优势
        insights = self._extract_insights(aspect_summary, aspect_details)
        
        # 4. 生成改进建议
        recommendations = self._generate_recommendations(aspect_summary, insights)
        
        # 5. 构建完整报告
        report = {
            "报告信息": {
                "产品名称": product_name,
                "生成时间": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "分析版本": "路由器方面级情感分析 v1.0",
                "评论总数": len(analyzed_data),
                "有效分析数": len([d for d in analyzed_data if d["aspect_analysis"]["mention_count"] > 0])
            },
            "方面情感汇总": aspect_summary,
            "方面详细分析": aspect_details,
            "关键洞察": insights,
            "改进建议": recommendations
        }
        
        # 生成文字报告
        text_report = self._generate_text_report(report)
        
        # 保存报告
        self._save_reports(report, text_report, output_path)
        
        return report
    
    def _summarize_aspect_sentiments(self, data):
        """汇总方面情感数据"""
        aspect_stats = {}
        
        for aspect_name in self.router_aspects.keys():
            scores = []
            confidences = []
            mention_count = 0
            intensity_counts = Counter()
            
            for item in data:
                aspect_result = item["aspect_analysis"]["aspect_results"].get(aspect_name, {})
                
                if aspect_result.get("mentioned", False):
                    mention_count += 1
                    score = aspect_result.get("sentiment_score", 0)
                    confidence = aspect_result.get("confidence", 0)
                    intensity = aspect_result.get("intensity_level", "一般")
                    
                    if confidence > 0.1:  # 只统计有效分析
                        scores.append(score)
                        confidences.append(confidence)
                        intensity_counts[intensity] += 1
            
            # 计算统计指标
            if scores:
                avg_score = np.mean(scores)
                score_std = np.std(scores)
                avg_confidence = np.mean(confidences)
                satisfaction_rate = len([s for s in scores if s > 0.2]) / len(scores) * 100
            else:
                avg_score = 0.0
                score_std = 0.0
                avg_confidence = 0.0
                satisfaction_rate = 0.0
            
            aspect_stats[aspect_name] = {
                "描述": self.router_aspects[aspect_name],
                "提及次数": mention_count,
                "提及率": round(mention_count / len(data) * 100, 1),
                "平均得分": round(avg_score, 3),
                "得分标准差": round(score_std, 3),
                "平均置信度": round(avg_confidence, 3),
                "满意度": round(satisfaction_rate, 1),
                "强度分布": dict(intensity_counts),
                "主要态度": max(intensity_counts.items(), key=lambda x: x[1])[0] if intensity_counts else "无提及"
            }
        
        # 按提及次数排序
        sorted_aspects = sorted(aspect_stats.items(), key=lambda x: x[1]["提及次数"], reverse=True)
        
        return {
            "方面统计": dict(sorted_aspects),
            "最受关注方面": sorted_aspects[0][0] if sorted_aspects else "无",
            "满意度最高": max(aspect_stats.items(), key=lambda x: x[1]["平均得分"])[0] if aspect_stats else "无",
            "满意度最低": min(aspect_stats.items(), key=lambda x: x[1]["平均得分"])[0] if aspect_stats else "无"
        }
    
    def _analyze_aspect_details(self, data):
        """分析各方面的详细情况"""
        aspect_details = {}
        
        for aspect_name in self.router_aspects.keys():
            positive_comments = []
            negative_comments = []
            common_phrases = Counter()
            common_keywords = Counter()
            
            for item in data:
                aspect_result = item["aspect_analysis"]["aspect_results"].get(aspect_name, {})
                
                if aspect_result.get("mentioned", False) and aspect_result.get("confidence", 0) > 0.2:
                    score = aspect_result.get("sentiment_score", 0)
                    
                    # 收集正负面评论样本
                    if score > 0.4:
                        positive_comments.append({
                            "内容": aspect_result.get("relevant_sentences", [""])[0][:80] + "...",
                            "得分": score
                        })
                    elif score < -0.4:
                        negative_comments.append({
                            "内容": aspect_result.get("relevant_sentences", [""])[0][:80] + "...",
                            "得分": score
                        })
                    
                    # 统计常见短语和关键词
                    for phrase in aspect_result.get("sentiment_phrases", []):
                        common_phrases[phrase["phrase"]] += 1
                    
                    for keyword in aspect_result.get("matched_keywords", []):
                        common_keywords[keyword] += 1
            
            # 排序并取前几个
            positive_comments.sort(key=lambda x: x["得分"], reverse=True)
            negative_comments.sort(key=lambda x: x["得分"])
            
            aspect_details[aspect_name] = {
                "正面评论样本": positive_comments[:3],
                "负面评论样本": negative_comments[:3],
                "常见情感短语": dict(common_phrases.most_common(5)),
                "热门关键词": dict(common_keywords.most_common(5))
            }
        
        return aspect_details
    
    def _extract_insights(self, aspect_summary, aspect_details):
        """提取关键洞察"""
        stats = aspect_summary["方面统计"]
        
        # 找出优势和劣势
        strengths = []
        weaknesses = []
        opportunities = []
        
        for aspect_name, data in stats.items():
            avg_score = data["平均得分"]
            mention_rate = data["提及率"]
            satisfaction = data["满意度"]
            
            if avg_score > 0.3 and mention_rate > 10:
                strengths.append({
                    "方面": aspect_name,
                    "原因": f"平均得分{avg_score:.2f}，满意度{satisfaction:.1f}%",
                    "表现": "优秀"
                })
            elif avg_score < -0.3 and mention_rate > 10:
                weaknesses.append({
                    "方面": aspect_name,
                    "原因": f"平均得分{avg_score:.2f}，满意度{satisfaction:.1f}%",
                    "严重程度": "需要关注" if avg_score > -0.5 else "急需改进"
                })
            elif mention_rate < 5:
                opportunities.append({
                    "方面": aspect_name,
                    "原因": f"提及率仅{mention_rate:.1f}%，关注度较低",
                    "机会": "可加强宣传或改进"
                })
        
        return {
            "产品优势": strengths,
            "改进要点": weaknesses,
            "潜在机会": opportunities,
            "整体表现": self._evaluate_overall_performance(stats)
        }
    
    def _evaluate_overall_performance(self, stats):
        """评估整体表现"""
        scores = [data["平均得分"] for data in stats.values() if data["提及次数"] > 0]
        satisfactions = [data["满意度"] for data in stats.values() if data["提及次数"] > 0]
        
        if not scores:
            return "数据不足，无法评估"
        
        avg_score = np.mean(scores)
        avg_satisfaction = np.mean(satisfactions)
        
        if avg_score > 0.3 and avg_satisfaction > 70:
            return "表现优秀，用户整体满意度高"
        elif avg_score > 0.1 and avg_satisfaction > 60:
            return "表现良好，多数用户满意"
        elif avg_score > -0.1 and avg_satisfaction > 50:
            return "表现中等，存在改进空间"
        elif avg_score > -0.3:
            return "表现偏差，需要重点改进"
        else:
            return "表现较差，急需全面改进"
    
    def _generate_recommendations(self, aspect_summary, insights):
        """生成改进建议"""
        stats = aspect_summary["方面统计"]
        recommendations = []
        
        # 基于劣势生成建议
        for weakness in insights["改进要点"]:
            aspect_name = weakness["方面"]
            
            if aspect_name == "网络性能":
                recommendations.append({
                    "方面": aspect_name,
                    "建议": "优化网络芯片和天线设计，提升数据传输速度",
                    "优先级": "高"
                })
            elif aspect_name == "信号稳定性":
                recommendations.append({
                    "方面": aspect_name,
                    "建议": "改进固件稳定性，优化连接算法，减少掉线情况",
                    "优先级": "高"
                })
            elif aspect_name == "信号覆盖":
                recommendations.append({
                    "方面": aspect_name,
                    "建议": "增强天线功率，优化信号传播算法，改善穿墙效果",
                    "优先级": "中"
                })
            elif aspect_name == "易用性":
                recommendations.append({
                    "方面": aspect_name,
                    "建议": "简化设置流程，改进管理界面，完善说明文档",
                    "优先级": "中"
                })
            elif aspect_name == "散热性能":
                recommendations.append({
                    "方面": aspect_name,
                    "建议": "优化散热设计，加强温控管理，降低运行噪音",
                    "优先级": "中"
                })
            elif aspect_name == "价格性价比":
                recommendations.append({
                    "方面": aspect_name,
                    "建议": "重新评估定价策略，或增加产品附加值",
                    "优先级": "低"
                })
        
        # 基于机会生成建议
        for opportunity in insights["潜在机会"]:
            aspect_name = opportunity["方面"]
            recommendations.append({
                "方面": aspect_name,
                "建议": f"加强{aspect_name}相关功能的宣传推广，提高用户认知度",
                "优先级": "低"
            })
        
        return recommendations
    
    def _generate_text_report(self, report):
        """生成文字版报告"""
        info = report["报告信息"]
        summary = report["方面情感汇总"]
        insights = report["关键洞察"]
        recommendations = report["改进建议"]
        
        text_lines = []
        text_lines.append(f"{'='*60}")
        text_lines.append(f"路由器产品方面级情感分析报告")
        text_lines.append(f"{'='*60}")
        text_lines.append(f"产品名称: {info['产品名称']}")
        text_lines.append(f"生成时间: {info['生成时间']}")
        text_lines.append(f"分析样本: {info['评论总数']} 条评论 (有效分析: {info['有效分析数']} 条)")
        text_lines.append("")
        
        # 执行摘要
        text_lines.append("📊 执行摘要")
        text_lines.append("-" * 40)
        text_lines.append(f"整体表现: {insights['整体表现']}")
        text_lines.append(f"最受关注方面: {summary['最受关注方面']}")
        text_lines.append(f"表现最佳方面: {summary['满意度最高']}")
        text_lines.append(f"改进重点方面: {summary['满意度最低']}")
        text_lines.append("")
        
        # 方面详细分析
        text_lines.append("🔍 方面详细分析")
        text_lines.append("-" * 40)
        
        stats = summary["方面统计"]
        # 按平均得分排序显示
        sorted_by_score = sorted(stats.items(), key=lambda x: x[1]["平均得分"], reverse=True)
        
        for aspect_name, data in sorted_by_score:
            if data["提及次数"] > 0:
                score_indicator = "😊" if data["平均得分"] > 0.2 else ("😐" if data["平均得分"] > -0.2 else "😞")
                text_lines.append(f"{score_indicator} {aspect_name}:")
                text_lines.append(f"   提及率: {data['提及率']}% | 满意度: {data['满意度']}% | 平均得分: {data['平均得分']}")
                text_lines.append(f"   主要态度: {data['主要态度']} | 描述: {data['描述']}")
                text_lines.append("")
        
        # 关键发现
        text_lines.append("💡 关键发现")
        text_lines.append("-" * 40)
        
        if insights["产品优势"]:
            text_lines.append("✅ 产品优势:")
            for strength in insights["产品优势"]:
                text_lines.append(f"   • {strength['方面']}: {strength['原因']}")
            text_lines.append("")
        
        if insights["改进要点"]:
            text_lines.append("⚠️ 需要改进:")
            for weakness in insights["改进要点"]:
                text_lines.append(f"   • {weakness['方面']}: {weakness['原因']} ({weakness['严重程度']})")
            text_lines.append("")
        
        if insights["潜在机会"]:
            text_lines.append("🔄 潜在机会:")
            for opportunity in insights["潜在机会"]:
                text_lines.append(f"   • {opportunity['方面']}: {opportunity['原因']}")
            text_lines.append("")
        
        # 改进建议
        if recommendations:
            text_lines.append("📈 改进建议")
            text_lines.append("-" * 40)
            
            # 按优先级分组
            high_priority = [r for r in recommendations if r["优先级"] == "高"]
            medium_priority = [r for r in recommendations if r["优先级"] == "中"]
            low_priority = [r for r in recommendations if r["优先级"] == "低"]
            
            if high_priority:
                text_lines.append("🔴 高优先级:")
                for rec in high_priority:
                    text_lines.append(f"   • {rec['方面']}: {rec['建议']}")
                text_lines.append("")
            
            if medium_priority:
                text_lines.append("🟡 中优先级:")
                for rec in medium_priority:
                    text_lines.append(f"   • {rec['方面']}: {rec['建议']}")
                text_lines.append("")
            
            if low_priority:
                text_lines.append("🟢 低优先级:")
                for rec in low_priority:
                    text_lines.append(f"   • {rec['方面']}: {rec['建议']}")
                text_lines.append("")
        
        text_lines.append("=" * 60)
        text_lines.append("报告结束")
        
        return "\n".join(text_lines)
    
    def _save_reports(self, json_report, text_report, output_path):
        """保存报告文件"""
        try:
            # 保存JSON格式
            json_path = output_path.replace('.txt', '.json')
            with open(json_path, 'w', encoding='utf-8') as f:
                json.dump(json_report, f, ensure_ascii=False, indent=2)
            
            # 保存文本格式
            txt_path = output_path
            with open(txt_path, 'w', encoding='utf-8') as f:
                f.write(text_report)
            
            print(f"✅ 报告已保存:")
            print(f"   📄 文本报告: {txt_path}")
            print(f"   📊 数据报告: {json_path}")
            
        except Exception as e:
            print(f"❌ 保存报告失败: {e}")

def main():
    """主处理流程"""
    print("🚀 启动路由器方面级情感分析...")
    
    # 配置路径
    sentiment_dict_path = "data/dictionaries/optimized_router_sentiment_dict.json"
    enhanced_data_dir = "advanced_analysis"
    output_dir = "aspect_analysis"
    
    # 确保输出目录存在
    os.makedirs(output_dir, exist_ok=True)
    
    # 初始化分析器和报告生成器
    analyzer = RouterAspectSentimentAnalyzer(sentiment_dict_path)
    report_generator = AspectReportGenerator()
    
    # 处理所有增强分析结果文件
    for filename in os.listdir(enhanced_data_dir):
        if filename.endswith('_enhanced.json'):
            print(f"\n{'='*60}")
            print(f"📁 处理文件: {filename}")
            
            input_path = os.path.join(enhanced_data_dir, filename)
            
            try:
                # 加载数据
                with open(input_path, 'r', encoding='utf-8') as f:
                    product_data = json.load(f)
                
                product_name = product_data.get('product_name', '未知产品')
                print(f"🔍 产品: {product_name}")
                
                comments = product_data.get("comments", [])
                if not comments:
                    print("⚠️ 无评论数据，跳过")
                    continue
                
                # 执行方面级分析
                aspect_analyzed_comments = analyzer.batch_analyze_aspects(comments)
                
                # 生成报告
                base_name = filename.replace('_enhanced.json', '')
                report_txt_path = os.path.join(output_dir, f"{base_name}_aspect_report.txt")
                
                aspect_report = report_generator.generate_aspect_report(
                    aspect_analyzed_comments, product_name, report_txt_path)
                
                # 保存增强后的评论数据
                product_data["comments"] = aspect_analyzed_comments
                product_data["aspect_analysis_info"] = {
                    "analysis_type": "路由器方面级情感分析",
                    "analysis_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    "analyzed_aspects": list(analyzer.router_aspects.keys())
                }
                
                aspect_data_path = os.path.join(output_dir, f"{base_name}_aspect_data.json")
                with open(aspect_data_path, 'w', encoding='utf-8') as f:
                    json.dump(product_data, f, ensure_ascii=False, indent=2)
                
                print(f"✅ 方面级分析完成:")
                print(f"   📊 分析报告: {report_txt_path}")
                print(f"   📈 分析数据: {aspect_data_path}")
                
                # 打印简要统计
                summary = aspect_report["方面情感汇总"]
                print(f"   📈 分析统计:")
                print(f"     最受关注: {summary['最受关注方面']}")
                print(f"     表现最佳: {summary['满意度最高']}")
                print(f"     改进重点: {summary['满意度最低']}")
                
            except Exception as e:
                print(f"❌ 处理 {filename} 失败: {e}")
                continue
    
    print(f"\n🎉 方面级情感分析完成！结果保存在 {output_dir} 目录")
    print("📋 生成的文件包括:")
    print("   • *_aspect_report.txt - 文字分析报告")
    print("   • *_aspect_report.json - 结构化分析数据")
    print("   • *_aspect_data.json - 完整分析数据")

if __name__ == "__main__":
    main()